import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/base/loading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

import '../JhPickerTool.dart';
import '../app_constant.dart';
import '../app_main/app_main.dart';
import '../app_utils.dart';
import '../net/method/base_method.dart';
import '../net/network_manager.dart';
import '../net/response/base_response.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController textEditingController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  String _username, _password, warehouse = '';
  bool passwordVisible = true;
  WarehouseUserName warehouseUserName;
  List<String> warehouses;

  @override
  void initState() {
    super.initState();

    Utils.getSharedPreferenceString(Constants.username).then((value) => {
          if (!Utils.isEmpty(value))
            {
              _username = value,
              setState(() {
                textEditingController.text = value;
                print("value:${value}");
              }),
              getWarehouseByUserName(value)
            }
        });
  }

  // 下拉菜单更新选择
  void _updateWarehouse(String value) {
    setState(() {
      warehouse = value ?? '';
      print('warehouse::' + warehouse);
    });
  }

//统一定义一个圆角样式
  var customBorder = OutlineInputBorder(borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(style: BorderStyle.none));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: null,
        body: Container(
          color: MyAppTheme.white,
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.only(left: 15, top: 100, right: 15),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Image.asset(
                      'assets/images/ic_logo.jpg',
                      width: 100,
                      height: 100,
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 20),
                    ),
                    ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 40),
                      child: TextField(
                        controller: textEditingController,
                        textInputAction: TextInputAction.next,
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "Username is required",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
                        ),
                        onChanged: (text) {
                          if (text == null) {
                            _username = text;
                            return;
                          }
                          if ((_username != null) && (_username == text)) {
                            return;
                          }
                          _username = text;
                          if (warehouses != null) {
                            warehouses.clear();
                          }
                          _updateWarehouse("");
                          print('First text field: $text (${text.characters.length})');
                          getWarehouseByUserName(text);
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10),
                    ),
                    ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 40),
                      child: TextFormField(
                        // autofocus: true,
                        obscureText: passwordVisible,
                        textInputAction: TextInputAction.next,
                        keyboardType: TextInputType.visiblePassword,
                        decoration: InputDecoration(
                          suffixIcon: IconButton(
                            icon: Icon(
                              passwordVisible ? Icons.visibility : Icons.visibility_off,
                              size: 25,
                              color: MyAppTheme.nearlyBlue,
                            ),
                            onPressed: () {
                              setState(() {
                                passwordVisible = !passwordVisible;
                              });
                            },
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "Password is required",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
                        ),
                        onChanged: (text) {
                          _password = text;
                          if (text == null) {
                            return;
                          }
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10),
                    ),
                    SizedBox(
                      height: 40, // 高度
                      width: double.infinity,
                      child: ElevatedButton(
                        child: Text(
                          warehouse,
                          style: TextStyle(
                            color: MyAppTheme.darkText,
                          ),
                        ),
                        style: ButtonStyle(
                          textStyle: MaterialStateProperty.all(
                            Theme.of(context).textTheme.subtitle1,
                          ),
                          alignment: Alignment.centerLeft,
                          elevation: MaterialStateProperty.all(0),
                          backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
                          shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              side: BorderSide(width: 1, color: MyAppTheme.nearlyBlue),
                              borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                            ),
                          ),
                        ),
                        onPressed: () {
                          // 请求焦点
                          FocusScope.of(context).requestFocus(FocusNode());
                          if (warehouses == null || warehouses.length == 0) {
                            return;
                          }
                          JhPickerTool.showStringPicker(context, data: warehouses, clickCallBack: (int index, var str) {
                            print(index);
                            print(str);
                            if (warehouses == null) {
                              _updateWarehouse("");
                              return;
                            }
                            if (warehouses.length <= index) {
                              _updateWarehouse("");
                              return;
                            }

                            _updateWarehouse(warehouses[index]);
                          });
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 50),
                    ),
                    SizedBox(
                      height: 40, // 高度
                      child: ElevatedButton(
                        child: Text('Login'),
                        style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
                          shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                            ),
                          ),
                        ),
                        onPressed: () {
                          ToastContext().init(context);

                          if (_username == null || _username.isEmpty) {
                            Toast.show("Please enter a user name", duration: Toast.lengthShort, gravity: Toast.bottom);
                            return;
                          }
                          if (_password == null || _password.isEmpty) {
                            Toast.show("Please enter a password", duration: Toast.lengthShort, gravity: Toast.bottom);
                            return;
                          }
                          if (warehouse == null || warehouse.isEmpty) {
                            Toast.show("Please enter a location", duration: Toast.lengthShort, gravity: Toast.bottom);
                            return;
                          }

                          login(context, _username, _password, warehouse);
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ));
  }

  void getWarehouseByUserName(String text) async {
    Map<String, dynamic> map = new HashMap();
    map['userName'] = text;

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getWarehouseByUserName, params: map);
    // warehouseUserName = WarehouseUserName.fromJson(baseResponse.data);
    List<String> warehouseList = new List<String>.from(baseResponse.data);
    if (warehouseList == null) {
      warehouses.clear();
      _updateWarehouse("");
      return;
    }
    warehouses = warehouseList;

    if (warehouses != null && warehouses.length > 0) {
      _updateWarehouse(warehouses[0]);
      var sp = await SharedPreferences.getInstance();
      sp.setStringList(Constants.warehouses, warehouses);
    } else {
      _updateWarehouse("");
    }
  }
}

class WarehouseUserName {
  int code;
  String message;
  List<String> data;

  WarehouseUserName(this.code, this.message, this.data);

  WarehouseUserName.fromJson(Map<dynamic, dynamic> json)
      : code = json['code'] as int,
        message = json['message'] as String,
        data = new List<String>.from(json['data']);
}

void login(BuildContext context, String username, String password, String location) async {
  LoginQr loginQr = LoginQr(username, password, location, "pda");

  // 显示加载中对话框
  LoadingIndicator.show(context, title: "Logging...");

  ///发送 FormData:
  String json = jsonEncode(loginQr);
  BaseResponse baseResponse = await NetworkManager().request(context, Constants.login, method: BaseMethod.post, data: json);
  LoadingIndicator.hide();

  print(baseResponse.code);
  if (baseResponse.code == 200) {
    LoginData loginData = LoginData.fromJson(baseResponse.data);
    var sp = await SharedPreferences.getInstance();
    sp.setString(Constants.token, loginData.token);
    sp.setString(Constants.username, username);
    sp.setString(Constants.location, location);
    Constants.tokenValue = loginData.token;
    Constants.usernameValue = username;
    Constants.locationValue = location;

    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(builder: (context) => MyAppMain()),
      (route) => route == null,
    );
  } else {
    ToastContext().init(context);
    Toast.show(baseResponse.message, duration: Toast.lengthShort, gravity: Toast.bottom);
  }
}

class LoginQr {
  String username;
  String password;
  String location;
  String platform;

  LoginQr(this.username, this.password, this.location, this.platform);

  Map<String, dynamic> toJson() => {
        'username': username,
        'password': password,
        'location': location,
        'platform': platform,
      };
}

class LoginData {
  String token;
  String username;
  List<dynamic> roles;
  List<dynamic> warehouseCodes;

  LoginData.fromJson(Map<String, dynamic> json)
      : token = json['token'] as String,
        username = json['username'] as String,
        roles = json['roles'] as List<dynamic>,
        warehouseCodes = json['warehouseCodes'] as List<dynamic>;
}
